import json
from datetime import datetime

from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.hourses.models import House
from apps.orders.models import Order
from utils.Audit_comment import Audit
from utils.es_search import index
from utils.login_required import LoginRequiredJSONMixin
from utils.send_message import url


# Create your views here.

redis_conn = get_redis_connection()




# 这是添加订单的视图
class OrderView(LoginRequiredJSONMixin,APIView):
    def post(self, request):
        data = request.data
        house_id = data.get('house_id')
        start_date = data.get('start_date')
        end_date = data.get('end_date')
        datetime1 = datetime.strptime(start_date, "%Y-%m-%d")
        datetime2 = datetime.strptime(end_date, "%Y-%m-%d")
        difference = (datetime2 - datetime1).days
        house = House.objects.get(id=house_id)
        amount = house.price * difference
        if house.min_days <= difference <= (house.max_days if house.max_days > 0 else float('inf')):
            order = Order.objects.create(house=house, user=request.user, begin_date=start_date, end_date=end_date,
                                         amount=amount, status=0, house_price=house.price, days=difference)
            # 使用 Elasticsearch 创建订单信息
            body = {
                    "id":order.id,
                    "end_date": order.end_date,
                    "begin_date": order.begin_date,
                    "house_id": order.house.id,
                    "status" : order.status,
                }
            index(body, 'order', 'index',order.id)
        else:
            return Response({'errno': 400, 'errmsg': '下单失败'})
        return Response({"data": {"order_id": order.id}, "errno": "0", "errmsg": "下单成功"})

    def get(self, request):
        role = request.GET.get('role')
        list_data = []
        if role == 'custom':
            order = Order.objects.filter(user=request.user)
            for i in order:
                if i.user == request.user:
                    list_data.append({
                        "amount": i.amount,
                        "comment": i.comment,
                        "ctime": i.create_time.strftime("%Y-%m-%d"),
                        "days": i.days,
                        "end_date": i.end_date.strftime("%Y-%m-%d"),
                        "img_url": url + str(i.house.index_image_url),
                        "order_id": i.id,
                        "start_date": i.begin_date,
                        "status": Order.ORDER_STATUS_ENUM[i.status],
                        "title": i.house.title
                    })
        else:
            order = Order.objects.all()
            for i in order:
                if i.house.user == request.user:
                    list_data.append({
                        "amount": i.amount,
                        "comment": i.comment,
                        "ctime": i.create_time.strftime("%Y-%m-%d"),
                        "days": i.days,
                        "end_date": i.end_date.strftime("%Y-%m-%d"),
                        "start_date": i.begin_date,
                        "img_url": url + str(i.house.index_image_url),
                        "order_id": i.id,
                        "status": Order.ORDER_STATUS_ENUM[i.status],
                    })

        return Response({"data": {"orders": list_data}, "errmsg": "OK", "errno": "0"})



# 接单和拒单
class OrderStatusView(LoginRequiredJSONMixin,APIView):
    def put(self, request, order_id):
        action = request.data.get('action')
        reason = request.data.get('reason')
        if action == 'accept':
            order = Order.objects.get(id=order_id)
            order.status = 3
            order.save()
        elif action == 'reject':
            order = Order.objects.get(id=order_id)
            order.status = 6
            order.comment = reason
            order.save()
        return Response({
            "errno": "0",
            "errmsg": "操作成功"
        })

# 评价订单
class OrderCommentView(APIView):
    def put(self, request,order_id):
        comment = request.data.get('comment')
        res = Audit(comment)
        # 进行判断    所评论内容是否违反审核标准
        # 获取参数进行判断
        if res.get('conclusion') != '合规':
            return Response({'errno': 400, 'errmsg': '评论不可以包含违规内容'})
        if comment:
            order = Order.objects.get(id=order_id)
            order.comment = comment
            order.status = 4
            order.save()
        return Response({
            "errno": "0",
            "errmsg": "评论成功"
        })
